#include "advancedprotection.h"
#include "configmanager.h"
#include "protection.h"
#include <QCoreApplication>
#include <QThread>
#include <QProcess>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QDateTime>
#include <QNetworkInterface>

// 静态实例
AdvancedProtection* AdvancedProtection::s_instance = nullptr;

AdvancedProtection& AdvancedProtection::instance()
{
    if (!s_instance) {
        s_instance = new AdvancedProtection();
    }
    return *s_instance;
}

AdvancedProtection::AdvancedProtection(QObject *parent)
    : QObject(parent)
    , m_protectionTimer(new QTimer(this))
    , m_integrityTimer(new QTimer(this))
{

    // 连接定时器
    connect(m_protectionTimer, &QTimer::timeout, this, &AdvancedProtection::performPeriodicCheck);
    connect(m_integrityTimer, &QTimer::timeout, this, &AdvancedProtection::performIntegrityCheck);

    // 设置验证函数
    m_validators = {
        [this]() { return performCryptoValidation(); },
        [this]() { return performNetworkValidation(); },
        [this]() { return performMemoryValidation(); },
        [this]() { return performFileSystemValidation(); }
    };
}

AdvancedProtection::~AdvancedProtection()
{
    clearSensitiveData();
}

void AdvancedProtection::initializeProtection()
{
    if (m_state.isInitialized) {
        return;
    }


    // 1. 环境检测
    if (isRunningInSuspiciousEnvironment()) {
        triggerTrap("Suspicious environment detected");
        return;
    }

    // 2. 反调试检查
    if (!detectDebuggingAttempts()) {
        triggerTrap("Debugging detected");
        return;
    }

    // 3. 生成会话密钥
    m_state.sessionKey = generateSessionKey();

    // 4. 计算基准校验和
    m_state.checksums.push_back(calculateDynamicChecksum());

    // 5. 启动保护定时器 (随机间隔, 1-5分钟)
    int interval = QRandomGenerator::global()->bounded(60000, 300000);
    m_protectionTimer->start(interval);

    // 6. 启动完整性检查定时器 (随机间隔, 30秒-2分钟)
    int integrityInterval = QRandomGenerator::global()->bounded(30000, 120000);
    m_integrityTimer->start(integrityInterval);

    // 7. 设置陷阱
    setupTraps();

    // 8. 保护关键内存
    protectCriticalMemory();

    m_state.isInitialized = true;
    m_state.lastCheckTime = QDateTime::currentMSecsSinceEpoch();

}

AdvancedProtection::ValidationResult AdvancedProtection::validateLicense()
{
    ValidationResult result;
    result.isValid = false;
    result.trustLevel = 0;
    result.timestamp = QDateTime::currentMSecsSinceEpoch();
    result.sessionId = QString::number(QRandomGenerator::global()->generate(), 16);


    // Layer 1: 基础token检查 (保留兼容性)
    QString authToken = ConfigManager::getAuthToken();
    if (authToken.isEmpty()) {
        // 不直接返回，继续其他检查以迷惑逆向工程师
    } else {
        result.trustLevel += 20;
    }

    // Layer 2: 硬件绑定验证
    if (!validateHardwareBinding()) {
        result.trustLevel -= 30;
    } else {
        result.trustLevel += 25;
    }

    // Layer 3: 时间约束检查
    if (!checkTimeConstraints()) {
        result.trustLevel -= 20;
    } else {
        result.trustLevel += 15;
    }

    // Layer 4: 运行时完整性
    if (!verifyRuntimeIntegrity()) {
        result.trustLevel -= 25;
        triggerTrap("Runtime integrity violation");
    } else {
        result.trustLevel += 20;
    }

    // Layer 5: 动态算法验证
    int passedValidators = 0;
    for (auto& validator : m_validators) {
        if (validator()) {
            passedValidators++;
        }
    }
    result.trustLevel += passedValidators * 5;

    // Layer 6: 会话签名验证
    QByteArray signatureData = QString("%1%2%3").arg(authToken)
                                                .arg(result.timestamp)
                                                .arg(result.sessionId)
                                                .toUtf8();
    result.signature = QCryptographicHash::hash(signatureData + m_state.sessionKey,
                                               QCryptographicHash::Sha256);

    // 最终判定 - 需要至少70分信任度
    result.isValid = result.trustLevel >= 70;

    // 添加随机混淆 - 让破解者困惑
    if (QRandomGenerator::global()->bounded(100) < 5) {  // 5%的概率
        result.isValid = !result.isValid;
        QTimer::singleShot(100, [&result]() {
            result.isValid = !result.isValid; // 100ms后恢复
        });
    }


    return result;
}

bool AdvancedProtection::shouldAddWatermark()
{

    // 多层判定逻辑，不能简单绕过
    ValidationResult validation = validateLicense();

    // 基础判定
    bool needWatermark = !validation.isValid;

    // 额外的混淆逻辑
    if (validation.trustLevel > 50 && validation.trustLevel < 70) {
        // 灰色地带 - 随机决定
        needWatermark = QRandomGenerator::global()->bounded(2) == 0;
    }

    // 反调试陷阱
    if (detectDebuggingAttempts()) {
        needWatermark = true;
    }

    // 时间炸弹检查
    if (!checkTimeConstraints()) {
        needWatermark = true;
    }

    return needWatermark;
}

QString AdvancedProtection::generateDynamicWatermark()
{
    // 动态生成水印内容，让水印移除变得困难
    QStringList watermarkTexts = {
        "影谷长图处理大师",
        "LongImageReader - Trial Version",
        "未授权版本 - 请购买正版",
        "Demo Version - Buy Full License",
        QString("Trial - %1").arg(QDateTime::currentDateTime().toString("yyyy-MM"))
    };

    // 基于硬件ID和时间生成选择索引
    QString hwId = Protection::machineIDHashKey();
    qint64 timeStamp = QDateTime::currentMSecsSinceEpoch() / (1000 * 60 * 60); // 每小时变化
    uint hash = qHash(hwId + QString::number(timeStamp));
    int index = hash % watermarkTexts.size();

    QString selected = watermarkTexts[index];

    return selected;
}

bool AdvancedProtection::verifyRuntimeIntegrity()
{
    // 运行时完整性检查 - 检测关键函数是否被修改
    QByteArray currentChecksum = calculateDynamicChecksum();

    if (m_state.checksums.empty()) {
        m_state.checksums.push_back(currentChecksum);
        return true;
    }

    // 检查是否与任何已知的良好校验和匹配
    for (const auto& checksum : m_state.checksums) {
        if (currentChecksum == checksum) {
            return true;
        }
    }

    emit integrityViolation("Runtime checksum mismatch");
    return false;
}

bool AdvancedProtection::validateHardwareBinding()
{
    // 多重硬件特征绑定
    QString machineId = Protection::machineID();
    if (machineId.isEmpty() || machineId == "?") {
        return false;
    }

    // 获取网络接口MAC地址
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    QStringList macAddresses;
    for (const QNetworkInterface& netInterface : interfaces) {
        if (netInterface.flags().testFlag(QNetworkInterface::IsRunning) &&
            !netInterface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
            macAddresses << netInterface.hardwareAddress();
        }
    }

    if (macAddresses.isEmpty()) {
        return false;
    }

    // 生成硬件指纹
    QString fingerprint = machineId + macAddresses.join(",");
    QByteArray hash = QCryptographicHash::hash(fingerprint.toUtf8(), QCryptographicHash::Sha256);

    // 检查是否与存储的指纹匹配
    QString storedFingerprint = ConfigManager::getHardwareFingerprint();
    if (storedFingerprint.isEmpty()) {
        // 首次运行，保存指纹
        ConfigManager::setHardwareFingerprint(hash.toHex());
        return true;
    }

    bool matches = (storedFingerprint == hash.toHex());
    if (!matches) {
        emit suspiciousActivity("Hardware fingerprint mismatch");
    }

    return matches;
}

bool AdvancedProtection::checkTimeConstraints()
{
    // 时间炸弹机制 - 防止时间回溯攻击
    qint64 currentTime = getSecureTimestamp();
    qint64 lastKnownTime = ConfigManager::getLastKnownTime();

    if (lastKnownTime > 0 && currentTime < lastKnownTime - 300000) { // 5分钟容差
        emit suspiciousActivity("Time manipulation detected");
        return false;
    }

    // 更新最后已知时间
    ConfigManager::setLastKnownTime(currentTime);

    return true;
}

bool AdvancedProtection::detectDebuggingAttempts()
{
    // 多层反调试检查
    return Protection::performAntiDebugCheck() &&
           !isRunningInSuspiciousEnvironment() &&
           validateTimeIntegrity();
}

// === 私有实现函数 ===

bool AdvancedProtection::performCryptoValidation()
{
    // 加密验证 - 检查关键算法是否被篡改
    QString testData = "AdvancedProtectionTest";
    QByteArray encrypted = Protection::encryptAuthData(testData.toUtf8());
    QByteArray decrypted = Protection::decryptAuthData(encrypted);

    return QString::fromUtf8(decrypted) == testData;
}

bool AdvancedProtection::performNetworkValidation()
{
    // 网络验证 - 检查网络配置
    QString apiBase = ConfigManager::getApiBase();
    return !apiBase.isEmpty() && apiBase.startsWith("https://");
}

bool AdvancedProtection::performMemoryValidation()
{
    // 内存验证 - 检查关键数据结构
    return m_state.isInitialized && !m_state.sessionKey.isEmpty();
}

bool AdvancedProtection::performFileSystemValidation()
{
    // 文件系统验证 - 检查程序文件完整性
    QString appPath = QCoreApplication::applicationFilePath();
    QFileInfo info(appPath);
    return info.exists() && info.size() > 0;
}

void AdvancedProtection::setupTraps()
{
    // 设置各种陷阱来检测破解行为
    // 这些陷阱会在运行时监控关键函数调用
}

void AdvancedProtection::triggerTrap(const QString& reason)
{
    m_state.isUnderAttack = true;
    m_state.failureCount++;
    emit protectionTriggered(reason);

    // 渐进式防护措施
    if (m_state.failureCount >= 3) {
        // 严重安全违规 - 可以考虑退出程序或禁用功能
        clearSensitiveData();
    }
}

QByteArray AdvancedProtection::generateSessionKey()
{
    QString keyData = QString("%1%2%3")
                     .arg(Protection::machineIDHashKey())
                     .arg(QDateTime::currentMSecsSinceEpoch())
                     .arg(QRandomGenerator::global()->generate());
    return QCryptographicHash::hash(keyData.toUtf8(), QCryptographicHash::Sha256);
}

QByteArray AdvancedProtection::calculateDynamicChecksum()
{
    // 计算关键代码区域的校验和
    QString appPath = QCoreApplication::applicationFilePath();
    return Protection::calculateFileHash(appPath);
}

bool AdvancedProtection::isRunningInSuspiciousEnvironment()
{
    return detectVirtualMachine() || detectSandbox();
}

bool AdvancedProtection::detectVirtualMachine()
{
    // VM检测逻辑
#ifdef _WIN32
    // Windows VM检测
    QStringList vmIndicators = {
        "VMware", "VirtualBox", "VBOX", "QEMU", "Xen"
    };

    // 可以检查注册表、服务、硬件信息等
    return false; // 简化实现
#else
    return false;
#endif
}

bool AdvancedProtection::detectSandbox()
{
    // 沙箱检测逻辑
    // 检查文件系统、网络连接、用户交互等
    return false; // 简化实现
}

bool AdvancedProtection::validateTimeIntegrity()
{
    // 时间完整性验证
    static qint64 lastCheck = 0;
    qint64 now = QDateTime::currentMSecsSinceEpoch();

    if (lastCheck > 0) {
        qint64 elapsed = now - lastCheck;
        // 检查时间是否正常流逝
        if (elapsed < 0 || elapsed > 600000) { // 10分钟上限
            return false;
        }
    }

    lastCheck = now;
    return true;
}

qint64 AdvancedProtection::getSecureTimestamp()
{
    return QDateTime::currentMSecsSinceEpoch();
}

void AdvancedProtection::protectCriticalMemory()
{
    // 保护关键内存区域
    // 在实际实现中可以使用内存加密或其他技术
}

void AdvancedProtection::clearSensitiveData()
{
    // 清除敏感数据
    m_state.sessionKey.fill(0);
    m_state.checksums.clear();
}

void AdvancedProtection::performPeriodicCheck()
{
    if (m_state.isUnderAttack) {
        return; // 已检测到攻击，停止检查
    }


    if (!detectDebuggingAttempts() || !verifyRuntimeIntegrity()) {
        triggerTrap("Periodic security check failed");
    }

    // 随机化下次检查间隔
    int nextInterval = QRandomGenerator::global()->bounded(60000, 300000);
    m_protectionTimer->start(nextInterval);
}

void AdvancedProtection::performIntegrityCheck()
{
    if (!verifyRuntimeIntegrity()) {
        triggerTrap("Integrity check failed");
    }

    // 随机化下次检查间隔
    int nextInterval = QRandomGenerator::global()->bounded(30000, 120000);
    m_integrityTimer->start(nextInterval);
}